﻿using System;
using System.Web;
using System.Text.RegularExpressions;
using System.Xml.Linq;

namespace YTPD.Lib
{
  public class YoutubeVideo
  {
    public string Title { get; set; }
    public string Description { get; set; }
    public string Enclosure { get; set; }
    public string Thumbnail { get; set; }

    private string _link;
    public string Link
    {
      get { return _link; }
      set
      {
        var uri = new Uri(value);
        bool linkPointsToYoutube = uri.Host.EndsWith("youtube.com", StringComparison.CurrentCultureIgnoreCase);
        bool validVideoId = !string.IsNullOrEmpty(HttpUtility.ParseQueryString(uri.Query)["v"]);

        if (linkPointsToYoutube && validVideoId)
        {
          _link = value;
        }
        else
        {
          throw new InvalidYoutubeVideoException();
        }
      }
    }

    public string Player { get; set; }
    public string FlvUri { get; set; }

    public static YoutubeVideo FromSingleVideo(string uri)
    {
      var uriConverter = new UriConverter(new WebClientImpl());
      var videoId = uriConverter.GetVideoId(uri);
      var gdataUri = uriConverter.FromYoutubeVideoToGDataVideo(videoId);

      var webClient = new WebClientImpl();
      var responseXml = webClient.DownloadString(gdataUri);

      var responseDocument = XDocument.Parse(responseXml, LoadOptions.SetBaseUri);

      XNamespace atom = "http://www.w3.org/2005/Atom";
      var titleElement = responseDocument.Root.Element(atom + "title");
      var videoTitle = titleElement != null ? titleElement.Value : string.Empty;

      var flvUri = uriConverter.GetFlvUriFromYoutubeVideoUri(videoId);

      return string.IsNullOrEmpty(flvUri) ?
        null : new YoutubeVideo
         {
           FlvUri = flvUri,
           Link = uri,
           Title = videoTitle
         };
    }
  }

  public class InvalidYoutubeVideoException : Exception
  {
  }
}
